package com.aioz.security.service.impl;



import com.aioz.security.common.ResponseResult;
import com.aioz.security.entity.*;
import com.aioz.security.entity.vo.OnlineUser;
import com.aioz.security.mapper.EducationMapper;
import com.aioz.security.mapper.ProjectMapper;
import com.aioz.security.mapper.ResumeMapper;
import com.aioz.security.mapper.UserMapper;
import com.aioz.security.service.UserService;
import com.aioz.security.utils.RedisCache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Resource
    private EducationMapper educationMapper;

    @Resource
    private ProjectMapper projectMapper;

    @Resource
    private ResumeMapper resumeMapper;

    @Resource
    private RedisCache redisCache;


    @Override
    public ResponseResult getAllUsers(Integer currentPage, Integer size) {
        Page<User> page = new Page<>(currentPage, size);
        Page<User> userPage = userMapper.selectPage(page, null);
        List<User> users = userPage.getRecords();
        long total = userPage.getTotal();
        Map<String, Object> map = new HashMap<>();
        map.put("users", users);
        map.put("total", total);
        return new ResponseResult(200, map);
    }

    @Override
    public ResponseResult getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = ((LoginUser) authentication.getPrincipal()).getUser();
        return new ResponseResult(200,user);
    }

    @Override
    public ResponseResult onlineUsers() {
        Set<OnlineUser> onlineUsers = redisCache.getCacheSet("online:");
        for (OnlineUser onlineUser : onlineUsers) {
            LocalDateTime now = LocalDateTime.now();
            int hour = (now.getHour() - onlineUser.getOnlineTime().getHour());
            int minute =(now.getMinute() - onlineUser.getOnlineTime().getMinute());
            onlineUser.setTimeSpending(hour +" 小时 " + minute + "分钟");
        }
        List<OnlineUser> users = new ArrayList<>(onlineUsers);
        return new ResponseResult(200,users);
    }

    @Override
    public ResponseResult forcedOffline(Long userId) {
        Set<OnlineUser> onlineUsers = redisCache.getCacheSet("online:");
        OnlineUser user = onlineUsers.stream().filter(onlineUser -> Objects.equals(onlineUser.getId(), userId)).collect(Collectors.toList()).get(0);
        redisCache.deleteObject("login:"+userId);
        redisCache.deleteCacheSet("online:",user);
        return new ResponseResult(200,"该用户已被强制下线!");
    }

    @Override
    public ResponseResult getResumeInfo(Integer id) {
        Map<String, Object> map = getUserInfo(Long.valueOf(id));
        return new ResponseResult<>(200,map);
    }

    @Override
    public ResponseResult getOwnInfo() {
        //获取登录用户ID
        Long userId = getCurrentUserId();
        Map<String, Object> map = getUserInfo(userId);
        return new ResponseResult<>(200,map);
    }

    @Override
    public ResponseResult getCompanyUser() {
        //获取当前登录用户ID
        Long userId = getCurrentUserId();
        log.info("当前登录ID为{}  的用户查询所在企业的全部员工",userId);
        Integer companyId =  userMapper.getCompanyIdByUserId(userId);
        log.info("该员工所在企业的ID为{}",companyId);
        List<User> users = userMapper.getUsersByCompanyId(companyId);
        log.info("所在企业的员工信息{}",users);
        return new ResponseResult<>(200,users);
    }

    @Override
    public ResponseResult queryUserByName(String name,Integer companyId) {
        log.info("用户名 name{}",name);
        List<User> users = userMapper.getUsersByCompanyId(companyId);
        users = users.stream()
                .filter(user -> user.getUserName().contains(name))
                .collect(Collectors.toList());
        return new ResponseResult<>(200,users);
    }

    @Override
    @Transactional
    public ResponseResult updateUserInfo(User user) {
        update().eq("id",user.getId()).update(user);
        return new ResponseResult<>(200,"成功更新用户信息");
    }

    @Override
    public ResponseResult forbidUser(Integer id) {
        boolean isSuccess = update().eq("id", id).setSql("del_flag = 1").update();
        if(isSuccess){
            return new ResponseResult<>(200,"该用户已被禁用");
        }
        return new ResponseResult<>(200,"系统异常");
    }

    public Map<String,Object> getUserInfo(Long userId){
        QueryWrapper<Education> educationWrapper = new QueryWrapper<>();
        QueryWrapper<Project> projectWrapper = new QueryWrapper<>();
        QueryWrapper<Resume> resumeWrapper = new QueryWrapper<>();
        educationWrapper.eq("user_id",userId);
        projectWrapper.eq("user_id",userId);
        resumeWrapper.eq("user_id",userId);
        Education education = educationMapper.selectOne(educationWrapper);
        Project project = projectMapper.selectOne(projectWrapper);
        Resume resume = resumeMapper.selectOne(resumeWrapper);
        User user = userMapper.selectById(userId);
        HashMap<String,Object> map = new HashMap<>();
        map.put("education",education);
        map.put("project",project);
        map.put("resume",resume);
        map.put("userInfo",user);
        return map;
    }

    public Long getCurrentUserId(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getId();
    }
}
